package com.startx.core.config.holder;

import java.lang.reflect.Field;
import java.util.Objects;

import com.startx.core.system.model.StartxConfig;

public class ConfigHolder {

	private static StartxConfig config;
	
	public static void setConfig(String name,String value) throws Exception {
	
		if(Objects.isNull(config)) {
			config = new StartxConfig();
		}
		
		filling(name,value);
	}
	
	/**
	 * 填充数据
	 * @param name
	 * @param value
	 * @throws Exception 
	 * @throws  
	 */
	private static void filling(String name, String value) throws Exception {
		
		Class<?> clz = StartxConfig.class;
		Field field = clz.getDeclaredField(name);
			
		field.setAccessible(true);
		
		if(field.getName().equals(name)) {
			
			if(field.getType().equals(int.class) || field.getType().equals(Integer.class) )  {
				field.set(config,Integer.parseInt(value));
			} else if(field.getType().equals(long.class) || field.getType().equals(Long.class) )  {
				field.set(config,Long.parseLong(value));
			} else if(field.getType().equals(short.class) || field.getType().equals(Short.class) )  {
				field.set(config,Short.parseShort(value));
			} else if(field.getType().equals(float.class) || field.getType().equals(Float.class) )  {
				field.set(config,Float.parseFloat(value));
			} else if(field.getType().equals(double.class) || field.getType().equals(Double.class) )  {
				field.set(config,Double.parseDouble(value));
			} else if(field.getType().equals(boolean.class) || field.getType().equals(Boolean.class) )  {
				field.set(config,Boolean.parseBoolean(value));
			} else {
				field.set(config,value);
			}
		
		}
	}

	/**
	 * 获取配置对象
	 */
	public static StartxConfig getConfig() {
		
		if(Objects.isNull(config)) {
			throw new RuntimeException("配置尚未初始化");
		}
		
		return config;
	}
}
